import React, { Component } from 'react';
import { Tree, Form, Input } from 'antd';
import menusConfig from "../../../config/menusConfig"

const { TreeNode } = Tree;
const { Item } = Form

class PermissionTree extends Component {
  state={
    checkedKeys:this.props.role.menus
  }

  UNSAFE_componentWillMount(){
    this.menus=this.getmenus(menusConfig);
  }

  // 传递的属性更新时会执行的钩子函数
  UNSAFE_componentWillReceiveProps(nexProps){
    this.setState({
      checkedKeys:nexProps.role.menus
    })
  }

  getmenus=(menusConfig)=>{
    return menusConfig.reduce((pre,next)=>{
      if(next.children){
        pre.push(
          <TreeNode title={next.title} key={next.key} >
              {this.getmenus(next.children)}
          </TreeNode> 
        )
      }else{
        pre.push(
          <TreeNode title={next.title} key={next.key} />
        )
      }
      return pre
    },[])
  }

  onCheck=(checkedKeys)=>{
    this.setState({
      checkedKeys
    })
  }

  render() {
    return (
      <Form>
        <Item label="角色名称">
          <Input disabled value={this.props.role.roleName}></Input>
        </Item>
        <Item>
          <Tree
            checkable
            defaultExpandAll={true}
            checkedKeys={this.state.checkedKeys}
            onCheck={this.onCheck}
          >
            {this.menus}
          </Tree>
        </Item>
      </Form>

    );
  }
}

export default PermissionTree;